package org.example.judge_feign_api.config;



import feign.RequestInterceptor;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Field;

@Configuration
@Slf4j
public class FeignConfiguration {
    private static Field requestFacadeField;
    private static Field ServletRequestAttributes;
    static {
        try {
            // ServletRequestAttributes
            ServletRequestAttributes = ServletRequestAttributes.class.getDeclaredField("request");
            ServletRequestAttributes.setAccessible(true);

            // requestFacade反射获取方法
            requestFacadeField = RequestFacade.class.getDeclaredField("request");
            requestFacadeField.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 1. obtain request
//                final ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                RequestAttributes attributes1 = RequestContextHolder.getRequestAttributes();
                // 2. 兼容hystrix限流后，获取不到ServletRequestAttributes的问题（使拦截器直接失效）
                if(attributes1==null){
                    //已经存在的root
                    return;
                }
//                System.out.println(attributes1);
//                System.out.println(attributes1.getClass());
                try {
                    //反射获取 request --》 RequestFacade
                    Object o = ServletRequestAttributes.get(attributes1);

                    // 反射获取Request
                    Object o1 = requestFacadeField.get(o);
                    // 根据获取的Request 获取其请求头token
                    String token = ((Request) o1).getHeader("token");
//                    System.out.println(token);
                    requestTemplate.header("token",token);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

//                HttpServletRequest request =  attributes.getRequest();
//                String token = request.getHeader("token");
//                System.out.println(token);
                // 2. obtain request headers，and put it into openFeign RequestTemplate


            }
        };
    }
}
